//数据结构体包含currentUser（用户信息）和gameRecords（对战记录）
//currentUser包含username(用户名),isGuest(是否是游客),token(令牌，类似于id)三个元素
//gameRecords包含id(对战记录id),mode(游戏模式：ai,local,online),result(输赢:胜利,失败,平局),opponent(对手用户名),timestamp(时间),aiLevel(ai难度：简单,中等,困难,不是ai模式就值为假)
class GomokuApp {
    constructor() {
        this.currentUser = JSON.parse(localStorage.getItem('gomoku_currentUser'));
        this.gameRecords = JSON.parse(localStorage.getItem('gomoku_records')) || [];
        this.init();
    }

    init() {
        this.checkAuth();
        this.setupUI();
        this.setupEventListeners();
        this.loadGameRecords();
    }

    checkAuth() {
        if (!this.currentUser) {
            window.location.href = 'auth.html';
        }
    }

    setupUI() {
        const usernameEl = document.getElementById('usernameDisplay');
        if (this.currentUser) {
            usernameEl.textContent = this.currentUser.username;
            if (this.currentUser.isGuest) {
                usernameEl.innerHTML += ' <span class="badge bg-secondary">游客</span>';
            }
        }
        this.updateActiveNav('home-link');
    }

    setupEventListeners() {
        // 导航切换
        document.getElementById('home-link').addEventListener('click', (e) => {
            e.preventDefault();
            this.showView('home-view');
            this.updateActiveNav('home-link');
        });

        document.getElementById('records-link').addEventListener('click', (e) => {
            e.preventDefault();
            this.showView('records-view');
            this.updateActiveNav('records-link');
        });

        // 游戏模式按钮
        document.getElementById('start-ai-btn').addEventListener('click', () => this.showGameOptions('ai'));
        document.getElementById('start-local-btn').addEventListener('click', () => this.showGameOptions('local'));
        document.getElementById('start-online-btn').addEventListener('click', () => this.showGameOptions('online'));
        // document.getElementById('watch-btn').addEventListener('click', () => this.startGame('watch'));

        // 用户操作
        document.getElementById('logoutLink').addEventListener('click', (e) => {
            e.preventDefault();
            this.logout();
        });

        document.getElementById('profileLink').addEventListener('click', (e) => {
            e.preventDefault();
            this.showProfile();
        });

        // 记录操作
        document.getElementById('clear-records').addEventListener('click', () => {
            if (confirm('确定要清空所有对战记录吗？')) {
                this.clearRecords();
            }
        });

        // 模态框操作
        // document.getElementById('confirm-start').addEventListener('click', () => this.handleGameStart());
        document.getElementById('random-room').addEventListener('click', () => {
            document.getElementById('room-id').value = 'room_' + Math.random().toString(36).substr(2, 6);
        });
    }

    showView(viewId) {
        document.getElementById('home-view').classList.add('d-none');
        document.getElementById('records-view').classList.add('d-none');
        document.getElementById(viewId).classList.remove('d-none');
    }

    updateActiveNav(activeId) {
        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
        });
        document.getElementById(activeId).classList.add('active');
    }

    showGameOptions(mode) {
        const modal = new bootstrap.Modal(document.getElementById('gameModeModal'));
        
        document.getElementById('ai-options').classList.add('d-none');
        document.getElementById('local-options').classList.add('d-none');
        document.getElementById('online-options').classList.add('d-none');
        
        let title = '';
        switch(mode) {
            case 'ai':
                title = '人机对战设置';
                document.getElementById('ai-options').classList.remove('d-none');
                break;
            case 'local':
                title = '本地双人设置';
                document.getElementById('local-options').classList.remove('d-none');
                break;
            case 'online':
                title = '联机对战设置';
                document.getElementById('online-options').classList.remove('d-none');
                document.getElementById('room-id').value = '';
                break;
        }
        
        document.getElementById('modeModalTitle').textContent = title;
        document.getElementById('confirm-start').dataset.mode = mode;
        modal.show();
    }

    handleGameStart() {
        const modal = bootstrap.Modal.getInstance(document.getElementById('gameModeModal'));
        const mode = document.getElementById('confirm-start').dataset.mode;
        
        let queryParams = `?mode=${mode}`;
        
        switch(mode) {
            case 'ai':
                const aiLevel = document.getElementById('ai-level').value;
                const aiColor = document.getElementById('ai-color').value;
                queryParams += `&level=${aiLevel}&color=${aiColor}`;
                break;
            case 'local':
                const boardSize = document.getElementById('board-size').value;
                queryParams += `&size=${boardSize}`;
                break;
            case 'online':
                const roomId = document.getElementById('room-id').value.trim() || 
                              'room_' + Math.random().toString(36).substr(2, 6);
                queryParams += `&room=${encodeURIComponent(roomId)}`;
                break;
        }
        
        modal.hide();
        this.startGame(mode, queryParams);
    }

    startGame(mode, queryParams = '') {
        if (mode === 'watch') {
            window.location.href = `game.html?mode=watch`;
        } else {
            window.location.href = `game.html${queryParams}`;
        }
    }

    logout() {
        localStorage.removeItem('gomoku_currentUser');
        window.location.href = 'auth.html';
    }

    showProfile() {
        alert(`用户名: ${this.currentUser.username}\n身份: ${this.currentUser.isGuest ? '游客' : '注册用户'}`);
    }

    loadGameRecords() {
        const tbody = document.querySelector('#records-table tbody');
        tbody.innerHTML = '';
        
        const currentUser = this.currentUser || { token: '' };
        const userRecords = this.gameRecords
            .filter(record => record.userId === currentUser.token)
            .slice(0, 20);
        
        if (userRecords.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">暂无对战记录</td></tr>';
            return;
        }
        
        userRecords.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${this.getModeName(record.mode)}${record.aiLevel ? ` (${this.getAiLevelName(record.aiLevel)})` : ''}</td>
                <td><span class="badge ${this.getResultBadgeClass(record.result)}">${record.result}</span></td>
                <td>${record.opponent || '-'}</td>
                <td>${new Date(record.timestamp).toLocaleString()}</td>
                <td>${record.username || '未知用户'}</td>
                `;
                // <td><button class="btn btn-sm btn-outline-primary replay-btn" data-id="${record.id}">回放</button></td>
            tbody.appendChild(row);
        });
        
        // document.querySelectorAll('.replay-btn').forEach(btn => {
        //     btn.addEventListener('click', (e) => {
        //         const recordId = e.target.dataset.id;
        //         this.replayGame(recordId);
        //     });
        // });
    }

    clearRecords() {
        const currentUser = this.currentUser || { token: '' };
        this.gameRecords = this.gameRecords.filter(record => record.userId !== currentUser.token);
        localStorage.setItem('gomoku_records', JSON.stringify(this.gameRecords));
        this.loadGameRecords();
    }

    getModeName(mode) {
        const modes = {
            'ai': '人机对战',
            'local': '本地双人',
            'online': '联机对战',
            'watch': '观战模式'
        };
        return modes[mode] || mode;
    }

    getAiLevelName(level) {
        const levels = {
            'easy': '简单',
            'medium': '中等',
            'hard': '困难'
        };
        return levels[level] || level;
    }

    getResultBadgeClass(result) {
        const classes = {
            '胜利': 'bg-success',
            '失败': 'bg-danger',
            '平局': 'bg-secondary',
            '玩家1胜利': 'bg-primary',
            '玩家2胜利': 'bg-info'
        };
        return classes[result] || 'bg-warning text-dark';
    }

    // replayGame(recordId) {
    //     const record = this.gameRecords.find(r => r.id === recordId);
    //     if (record) {
    //         alert(`即将回放对战记录: ${record.id}\n${record.mode} ${record.result}`);
    //         // 实际项目中这里会跳转到回放页面
    //     }
    // }

    addRecord(result, opponent, mode, aiLevel) {
        const newRecord = {
            id: 'rec_' + Math.random().toString(36).substr(2, 9),
            mode,
            result,
            opponent,
            timestamp: new Date().toISOString(),
            aiLevel,
            userId: this.currentUser?.token || 'guest_' + Math.random().toString(36).substr(2, 9),
            username: this.currentUser?.username || '游客'
        };
        this.gameRecords.unshift(newRecord);
        localStorage.setItem('gomoku_records', JSON.stringify(this.gameRecords));
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new GomokuApp();
});